<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>拖拽</title>
    <style>
        *{
            margin: 0; padding: 0;
        }
        #div1{
            width: 200px;
            height: 200px;
            border: 1px solid #ccc;
            background-color: #eee;
            cursor: pointer;
            position: absolute;
            top: 50px;
            left: 50px;
        }
    </style>
</head>
<body>
  <div id="div1"></div>
  <script>
      var div1 = document.getElementById('div1');
      window.onload = function() {

        function mouseMove(e) {
            if (div1.isDown) {
                console.log('鼠标悬浮, 并移动')
                div1.style.left = e.clientX - div1.mouseOffsetX + 'px';
                div1.style.top = e.clientY - div1.mouseOffsetY + 'px';
            }
        }

        function mouseDown(e) {
            div1.isDown = true
            div1.mouseOffsetX = e.clientX - div1.offsetLeft;
            div1.mouseOffsetY = e.clientY - div1.offsetTop;
            
            document.addEventListener('mousemove', mouseMove)
        }

        function mouseUp() {
            console.log('鼠标离开')
            div1.isDown = false
            document.removeEventListener('mousemove', mouseMove)
        }

        div1.addEventListener('mousedown', mouseDown)
        document.addEventListener('mouseup', mouseUp)
      }
  </script>
</body>
</html>